<?php

namespace Zlf\Sms\Drive;

use Zlf\Sms\Drive\Config\Ztconfig;
use Zlf\Sms\SmsResult;
use Zlf\Request\Http;
use Zlf\Unit\Json;

/**
 * 助通科技短信
 * @link https://doc.zthysms.com/web/#/1/7
 */
class Ztsms extends SmsBasics
{

    protected $host = 'https://api.mix2.zthysms.com';

    const SEND_SMS_API = '/v2/sendSms';//发送模板短信api

    const BALANCE_API = '/v2/balance';//获取短信余额api


    /**
     * 获取短信配置
     * @return Ztconfig
     */
    protected function getConfig(): Ztconfig
    {
        return parent::getConfig(); // TODO: Change the autogenerated stub
    }


    public function getBalance(): int
    {
        $conf = $this->getConfig();
        $tKey = time();
        $data = [
            'username' => $conf->username,
            'password' => md5(md5($conf->password) . $tKey),
            'tKey' => $tKey
        ];
        $post = Http::post($conf->host . self::BALANCE_API, Json::encode($data), [
            'headers' => ['Content-Type: application/json; charset=utf-8'],
        ]);
        if (isset($post['result']) && $post['result']) {
            $body = Json::decode($post['result']);
            return intval($body['sumSms'] ?? 0);
        }
        return 0;
    }

    public function send(string $phone, string $template_key, array $data = []): SmsResult
    {
        $conf = $this->getConfig();
        $tKey = time();
        $content = $this->renderContent($conf->template, $template_key, array_merge($data, ['signature' => $conf->signature]));
        $postData = [
            'username' => $conf->username,
            'password' => md5(md5($conf->password) . $tKey),
            'tKey' => $tKey,
            'mobile' => $phone,
            'content' => $content
        ];
        $post = Http::post($this->host . self::SEND_SMS_API, Json::encode($postData), [
            'headers' => [
                'Content-Type: application/json; charset=utf-8'
            ],
        ]);
        $request = null;
        if (isset($post['result']) && $post['result']) {
            $request = Json::decode($post['result']);
            if (isset($request['msg']) && $request['msg'] === 'success') {
                return new SmsResult(['phone' => $phone, 'content' => $content, 'status' => true, 'driver' => static::class, 'template_key' => $template_key, 'request' => $request]);
            }
        }
        return new SmsResult(['phone' => $phone, 'content' => $content, 'status' => false, 'driver' => static::class, 'template_key' => $template_key, 'request' => $request]);
    }
}